<template>
	<view class="picadd">
		<custom-head-top>
			<template #left>
				新增壁纸
			</template>
		</custom-head-top>
	</view>

	<view class="main">
		<view class="grid">
			<view class="itemBox pic" v-for="(item, index) in piclist" :key="index">
				<view class="close" @click="handleClose(index)">x</view>
				<!-- <picEditItem :item="item" @update:item="piclist[index] = $event"></picEditItem> -->
				<!-- 还可以这样写 -->
				<picEditItem v-model:item="piclist[index]"></picEditItem>
			</view>
			<view class="itemBox add" @click="handleSelect" v-if="piclist.length < 9">
				<view class="icon">+</view>
				<view class="text">点击选择图片</view>
			</view>
		</view>

		<view class="setClassify" v-if="piclist.length">
			<uni-data-select ref="selectRef" @change="classifyChange" collection="xxm-bizhi-classify"
				field="_id as value, name as text, sort" label="请选择分类" :where="`enable == true`" orderBy="sort desc"
				clear placement="top" v-model="selectValue"></uni-data-select>
		</view>
		{{piclist}}
		<view class="btnGroup" v-if="piclist.length">
			<button class="btn" type="primary" @click="submit">发布</button>
			<button class="btn" type="warn" plain @click="handleReset">清空</button>
		</view>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import dayjs from 'dayjs';
	import { routerTo, showModal, showToast } from '@/utils/common.js'
	import { cloudToHttps, compressAndConvertToWebp } from '../../utils/tools';
	import picEditItem from './children/picEditItem.vue';

	const picCloudObj = uniCloud.importObject("admin-bizhi-picture");
	const piclist = ref([]);
	const selectValue = ref("")
	const selectRef = ref(null);

	//确认提交
	const submit = async () => {
		if (!checkClassify()) return;
		if (!checkDescription()) return;

		try {
			uni.showLoading({ mask: true });
			let uploadTasks = piclist.value.map((item, index) => uploadFile(item, index));
			let cloudFiles = await Promise.all(uploadTasks); //同时发送网络请求
			let params = piclist.value.map((item, index) => {
				let { tempurl, ...rest } = item;
				return {
					...rest,
					classid: selectValue.value,
					picurl: cloudToHttps(cloudFiles[index].fileID)
				}
			})
			let { errCode, errMsg } = await picCloudObj.add(params);
			if (errCode !== 0) return showToast({ title: errMsg });
			showToast({ title: "发布成功" });
			setTimeout(() => routerTo("/pages/bizhi/piclist", "redirect"), 1500);
			selectRef.value.clearVal(); //这句话的意思是的调用nui-data-select内部的方法，清除缓存
		} catch (err) {
			console.log(err);
			showToast({ title: err })
			uni.hideLoading();
		}


	}


	//上传图片
	const uploadFile = async (item, index) => {
		let tmpurl = await compressAndConvertToWebp(item.tempurl);
		return uniCloud.uploadFile({
			filePath: tmpurl,
			cloudPath: `wallpaper/${dayjs().format("YYYYMMDD")}/${Date.now()}_${index}.webp`
		})
		console.log(res);
	}


	//校验是否选择了分类
	const checkClassify = () => {
		if (!selectValue.value) {
			showToast({
				title: "请选择分类"
			})
			return false;
		}
		return true;
	}

	//校验是否填写图片描述
	const checkDescription = () => {
		//下边的这个方法意思是寻找每个description的值，如果全都存在则为true
		// let desRes = piclist.value.every(item => item.description);

		//这种方法可以找到具体哪个下标的数据没有值，可以直接提示出来
		let desIndex = piclist.value.map((item, index) => item.description ? null : index + 1)
			.filter(item => item != null).join(",");
		if (desIndex) {
			showToast({
				title: `第${desIndex}张图片的描述不能为空`
			})
			return false;
		}
		return true;
	}

	//选择上传图片
	const handleSelect = async () => {
		let imgs = await uni.chooseImage({
			count: 9
		})

		let obj = {
			description: "",
			score: "3.5",
			tabs: [],
			picurl: "",
			checked: true,
			tempurl: ""
		};

		piclist.value = [...piclist.value, ...imgs.tempFilePaths.map(item => ({
			...obj,
			tempurl: item
		}))];


		console.log(piclist.value);
	}

	//移除图片
	const handleClose = async (index) => {
		let feedback = await showModal({
			content: "是否确认移除"
		})
		if (feedback == "confirm") {
			piclist.value.splice(index, 1);
		}

	}

	//清空所有
	const handleReset = async () => {
		let feedback = await showModal({
			content: "是否全部移除"
		})
		if (feedback == "confirm") {
			piclist.value = [];
		}

	}

	//选择分类
	const classifyChange = (e) => {
		piclist.value.forEach(item => {
			item.classid = e;
		});
		console.log("-------------", e);
	}
</script>

<style lang="scss" scoped>
	.main {
		padding: 20px;

		.grid {
			display: grid;
			grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
			gap: 20px;

			.itemBox {
				background: #f8f8f8;
				width: 100%;
				min-height: 300px;
				border: 1px solid transparent;
				padding: 20px;
				position: relative;

				.close {
					position: absolute;
					top: 0px;
					right: 0px;
					width: 30px;
					height: 30px;
					background: #E43D33;
					color: #fff;
					display: none;
					justify-content: center;
					align-items: center;
					cursor: pointer;
				}
			}

			.itemBox.add {
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				color: #999;
				cursor: pointer;

				.icon {
					font-size: 50px;
				}

				.text {
					font-size: 20px;
					margin-top: 20px;
				}
			}

			.itemBox:hover {
				border-color: #e4e4e4;

				.close {
					display: flex;
				}
			}
		}

		.setClassify {
			padding: 30px 0;
			width: 430px;
		}

		.btnGroup {
			display: flex;
			margin: 0;
			gap: 30px;
			padding: 50px 0;
			width: 430px;

			button {
				width: 200px;
			}
		}
	}
</style>